<template>
  <div>
    <el-dialog
      :title="title ? title : type == 1 ? '新增账号' : '修改账号'"
      :visible="open"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="620px"
      append-to-body
      @close="cancel()"
    >
      <el-form
        @submit.native.prevent
        ref="form"
        :model="form"
        :rules="rules"
        label-width="110px"
      >
        <el-form-item label="大区" v-if="shopObject.regionName">
          {{ shopObject.regionName }}
        </el-form-item>
        <el-form-item label="门店" v-if="shopObject.schoolName">
          {{ shopObject.schoolName }}
        </el-form-item>
        <el-form-item label="用户头像" prop="avatar">
          <uploadAvatar
            :avatar="form.avatar"
            @refresh="uploadAvatarReturn"
          ></uploadAvatar>
        </el-form-item>
        <el-form-item label="账号(手机号)" prop="phoneNumber">
          <el-input
            v-input-restrict
            style="width: 95%"
            v-model="form.phoneNumber"
            placeholder="请输入手机号"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input
            v-input-restrict
            maxlength="10"
            show-word-limit
            @input="handleInput"
            style="width: 95%"
            v-model="form.name"
            placeholder="请输入姓名"
          />
        </el-form-item>
        <el-form-item label="用户性别">
          <el-radio-group v-model="form.sex">
            <el-radio
              v-for="dict in dict.type.sys_user_sex"
              :key="parseInt(dict.value)"
              :label="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="门店名称"
          prop="schoolIds"
          v-if="!shopObject.schoolName"
        >
          <el-select
            style="width: 95%"
            v-model="form.schoolIds"
            multiple
            filterable
            clearable
            placeholder="请选择门店"
            @change="schoolChange"
          >
            <el-option
              v-for="item in shopOptions"
              :key="item.schoolId"
              :label="item.schoolName"
              :value="item.schoolId"
              :disabled="item.status == 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 门店列表 -->
        <el-form-item
          prop="schoolPostList"
          label="门店列表"
          v-if="!shopObject.schoolName"
        >
          <div class="cardbox">
            <!-- 门店卡片 -->
            <el-card
              class="box-card"
              style="width: 95%"
              v-for="(card, index) in form.schoolPostList"
              :key="index"
            >
              <div slot="header" class="clearfix">
                <span
                  v-for="(shopOption, shopOptionIndex) in shopOptions"
                  :key="shopOptionIndex"
                  v-if="card.schoolId == shopOption.schoolId"
                >
                  {{ shopOption.schoolName }}
                </span>
                <i
                  @click="deleteCard(index)"
                  style="float: right; margin-top: 10px"
                  class="el-icon-close shou"
                ></i>
              </div>
              <div>
                <el-form
                  @submit.native.prevent
                  :ref="`card_form${card.schoolId}`"
                  :model="card"
                  :rules="rules"
                  label-width="80px"
                >
                  <el-form-item label="所属岗位" prop="postIds">
                    <el-select
                      @change="postChange($event, index)"
                      style="width: 95%"
                      v-model="card.postIds"
                      multiple
                      filterable
                      clearable
                      placeholder="请选择岗位"
                    >
                      <el-option
                        v-for="postOption in postOptions"
                        :key="postOption.postId"
                        :label="postOption.postName"
                        :value="postOption.postId"
                        v-if="postOption.status == 0"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
            </el-card>
          </div>
        </el-form-item>

        <el-form-item
          label="所属岗位"
          prop="postIds"
          v-if="shopObject.schoolName"
        >
          <el-select
            style="width: 95%"
            v-model="form.postIds"
            multiple
            filterable
            clearable
            placeholder="请选择岗位"
          >
            <el-option
              v-for="item in postOptions"
              :key="item.postId"
              :label="item.postName"
              :value="item.postId"
              v-if="item.status == 0"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick @click="cancel">取 消</el-button>
        <el-button v-preventReClick type="primary" @click="submitForm"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
  
<script>
import { listPost_school } from "@/api/school/list";
import { listPost } from "@/api/system/post";
import uploadAvatar from "@/components/uploadAvatar";
import { checkPhone } from "@/utils/validate";
import { getUser, addUser, updateUser } from "@/api/system/user";
import {
  listPost_student,
  getPost_student,
  addPost_student,
  updatePost_student,
} from "@/api/schoolOrganization/student";
const checkschoolPostList = (rule, value, callback) => {
  let allValid = true;
  for (let i = 0; i < value.length; i++) {
    if (value[i].postIds.length == 0) {
      allValid = false;
      callback(new Error(`请选择岗位`));
    }
  }
  if (allValid) {
    callback();
  }
};
export default {
  props: {
    open: Boolean,
    type: Number,
    // 编辑时候的用户id
    id: [String, Number],
    from: [String],
    title: {
      require: false,
      type: String,
    },
    // 当type==shopAdmin 添加门店管理员时候 则需要传入门店id
    shopObject: {
      require: false,
      type: [Object],
      default: () => ({}),
    },
  },
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: { uploadAvatar },
  data() {
    return {
      postIds: [],
      // 门店选项
      shopOptions: [],
      // 岗位选项
      postOptions: [],
      // 表单参数
      form: {
        schoolPostList: [],
        userId: undefined,
        schoolIds: [],
        userName: undefined,
        name: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: 0,
        remark: undefined,
        avatar: undefined,
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      cardRules: {
        postIds: [{ required: true, message: "岗位不能为空", trigger: "blur" }],
      },
      // 表单校验
      rules: {
        phoneNumber: [
          { required: true, validator: checkPhone(), trigger: "blur" },
        ],
        schoolPostList: [
          { required: true, validator: checkschoolPostList, trigger: "blur" },
        ],
        schoolIds: [
          { required: true, message: "门店不能为空", trigger: "blur" },
        ],
        postIds: [{ required: true, message: "岗位不能为空", trigger: "blur" }],
        name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
      },
    };
  },
  watch: {
    open(e) {
      if (e) {
        this.getshopList();
        this.getPostList();
        console.log("type", this.type);
        if (this.type == 1) {
          this.reset();
        } else {
          this.reset();
          getPost_student(this.id).then((response) => {
            response.data.schoolIds = response.data.schoolIds
              ? response.data.schoolIds.split(",").map((item) => {
                  return parseInt(item);
                })
              : [];
            // 如果在门店详情-员工情况里操作 则带入门店 显示岗位(需要处理)
            if (this.shopObject.schoolId) {
              response.data.postIds = response.data.postIds
                ? response.data.postIds.split(",").map((item) => {
                    return parseInt(item);
                  })
                : [];
            }

            this.form = response.data;
          });
        }
      }
    },
  },
  mounted() {},
  methods: {
    handleInput() {
      // 使用正则表达式来校验输入内容，只允许汉字和英文字符
      this.form.name = this.form.name.replace(/[^\u4E00-\u9FA5A-Za-z]/g, "");
    },

    /* 岗位下拉变化 */
    postChange(e, index) {
      this.$set(
        this.form.schoolPostList,
        index,
        this.form.schoolPostList[index]
      );
    },
    /* 删除卡片 */
    deleteCard(index) {
      // 通过index删除form.schoolIds中的数据
      this.form.schoolIds.splice(index, 1);
      this.form.schoolPostList.splice(index, 1);
    },
    /* 门店下拉框变化 生成门店卡片 */
    schoolChange(e) {
      console.log(e);
      // 先将之前的数据进行存储
      let schoolPostList = [...this.form.schoolPostList];
      // 将下拉款生成的数组 进行转化
      e = e.map((newItem, index) => {
        const existingItem = schoolPostList.find(
          (item) => item.schoolId === newItem
        );
        console.log(existingItem);
        if (existingItem) {
          // 找到对应 schoolId 的对象，将新的对象赋给它
          return {
            postIds: existingItem.postIds,
            schoolId: parseInt(existingItem.schoolId),
            schoolName: existingItem.schoolName,
            postNames: existingItem.postNames,
          };
        } else {
          return {
            postIds: [], // 新增的对象postIds为[ ]
            schoolId: parseInt(newItem),
            schoolName: null,
            postNames: null,
          };
        }
      });
      console.log("--------", e);
      this.form.schoolPostList = e;
    },
    /* 头像组件返回 */
    uploadAvatarReturn(e) {
      this.form.avatar = e;
    },
    /* 获取门店列表 */
    getshopList() {
      if (
        this.$store.getters.roles.length == 2 &&
        this.$store.getters.roles.includes("sa")
      ) {
        this.shopOptions = this.$store.getters.schoolPostList;
      } else {
        listPost_school({
          pageNum: 1,
          pageSize: 9999,
        }).then((res) => {
          this.shopOptions = res.rows;
        });
      }
    },
    /* 获取岗位 */
    getPostList() {
      listPost({
        pageNum: 1,
        pageSize: 9999,
      }).then((response) => {
        this.postOptions = response.rows;
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      console.log("提交按钮", this.$refs["form"]);
      this.$refs["form"].validate((valid) => {
        console.log(valid, this.shopObject);
        if (valid) {
          let data = { ...this.form };
          data.schoolIds = data.schoolIds.join(",");
          // 因为是门店详情-员工情况 进入 所以带有门店id
          if (this.shopObject.schoolId) {
            console.log(
              "因为是门店详情-员工情况 进入 所以带有门店id",
              this.shopObject.schoolId
            );
            data.schoolIds = this.shopObject.schoolId;
            data.schoolPostList = [
              {
                schoolId: this.shopObject.schoolId,
                postIds: this.form.postIds,
              },
            ];
            delete data.postIds;
            delete data.schoolIds;
          }
          if (this.form.studentId != undefined) {
            updatePost_student(data).then((response) => {
              this.$modal.msgSuccess("编辑成功");
              this.cancel();
              this.$emit("refresh", true);
            });
          } else {
            addPost_student(data).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.cancel();
              this.$emit("refresh", true);
            });
          }
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        schoolPostList: [],
        userId: undefined,
        schoolIds: [],
        userName: undefined,
        name: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: 0,
        remark: undefined,
        avatar: undefined,
      };
      this.resetForm("form");
    },
    // 表单重置
    cancel() {
      this.$emit("update:open", false);
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-dialog {
  margin-top: 2vh !important;
}
.cardbox {
  min-height: 110px;
  max-height: calc(100vh - 610px);
  overflow-y: scroll;
}
::v-deep .el-card__header {
  padding: 0 20px;
}
::v-deep .el-card__body {
  padding: 10px 20px 20px 20px;
}
.box-card {
  margin-top: 10px;
}
.box-card:nth-of-type(1) {
  margin-top: 0px;
}
</style>
  